$(function () {
    var historyBackTotal = 0,
        historyForwardTotal = 0,
        currentSearchBoxLiIndex = -1;

    $('body').on('click', '#back-page', function () {
        historyForwardTotal++;
        historyBackTotal--;

        window.history.back();
    })

    $('body').on('click', '#forward-page', function () {
        historyForwardTotal--;
        historyBackTotal++;

        window.history.forward();
    })

    $(document).pjax('a', '#pjax-container');
    //pjax 点击a链接完成后
    $(document).on('pjax:clicked', function () {
        historyBackTotal++;
        historyForwardTotal = 0;
    })
    //pjax 开始请求时
    $(document).on('pjax:start', function () {
        NProgress.start();
    });
    //pjax 请求完成后
    $(document).on('pjax:end', function () {
        if (historyBackTotal > 0) {
            $('#back-page').removeClass('hide').addClass('show');
        } else {
            $('#back-page').removeClass('show').addClass('hide');
        }
        if (historyForwardTotal > 0) {
            $('#forward-page').removeClass('hide').addClass('show');
        } else {
            $('#forward-page').removeClass('show').addClass('hide');
        }
        NProgress.done();
        updatehits();
    });
    //pjax 请求超时
    $(document).on("pjax:timeout", function (event) {
        // 阻止超时导致链接跳转事件发生
        event.preventDefault()
    });

    function updatehits() {
        $.get('/hits/name/' + $('#file_name').val())
    }

    $(document).on('click', '#jump_home', function () {
        $('#search_input').attr('data-oldval', '').val('');
        $('#home_url').trigger('click');
    })

    //搜索自动提示
    $(document).on('keyup', '#search_input', function (e) {
        e.stopPropagation();

        var code, $this = $(this);
        if (!e) {
            var e = window.event;
        }
        if (e.keyCode) {
            code = e.keyCode;
        } else if (e.which) {
            code = e.which;
        }
        if (code == 38 || code == 40) {
            return false;
        }

        var $this = $(this),
            newval = $.trim($this.val()),
            oldval = $.trim($this.attr('data-oldval'));
        if (!newval) {
            $('#search_auto_complete_box').html('').hide();
            return false;
        }

        if (newval == oldval) {
            return false;
        }

        $.ajax({
            url: '/search/ajax/keyword/' + newval,
            type: 'get',
            dateType: 'json',
            data: {},
            beforeSend: function () {

            },
            success: function (data) {
                if (data.length) {
                    var li_htmls = '';
                    $.each(data, function (i, v) {
                        var li_name = v.keyword;
                        if (v.keyword != v.title) {
                            li_name += ' - ' + v.title;
                        } else {
                            li_name += ' - ' + v.file_name;
                        }
                        var li_name_replace = li_name.replace(eval("/" + newval + "/ig"), '<label class="text-success">' + newval + '</label>');
                        li_htmls += '<li title="' + li_name + '"><a href="/' + v.file_name + '">' + li_name_replace + '</a></li>';
                    });
                    $('#search_auto_complete_box').html(li_htmls);
                    $('#search_auto_complete_box').show();
                } else {
                    $('#search_auto_complete_box').html('').hide();
                }
            },
            complete: function () {
                $this.attr('data-oldval', newval);
                $('#search_auto_complete_box').animate({scrollTop: 0}, 300);
            }
        })
        currentSearchBoxLiIndex = -1;
    })

    $(document).on('click', '#search_input', function (e) {
        e.stopPropagation();
    })

    $(document).on('click', function (e) {
        $('#search_auto_complete_box').hide();
        e.stopPropagation();
    })

    //滚动出现返回顶部按钮
    $(window).scroll(function () {
        if ($(window).scrollTop() > 100) {
            $("#topAffix").fadeIn(1500);
        }
        else {
            $("#topAffix").fadeOut(1500);
        }
    });

    //当点击跳转链接后，回到页面顶部位置
    $(document).on('click', '#topAffix', function () {
        $('body,html').animate({scrollTop: 0}, 500);
        return false;
    });

    //搜索表单提交事件
    $('#search-form').submit(function () {
        var keyword = $.trim($('#search_input').val());
        if (!keyword) {
            $('#search_input').focus();
            return false;
        }
    })

    /**
     * 自动搜索框上下键盘事件
     */
    $('#search_input').keydown(function (e) {
        var code = 0,
            $this = $(this),
            $ul = $('#search_auto_complete_box'),
            liNum = $ul.find('li').length;

        if (!e) {
            e = window.event;
        }
        if (e.keyCode) {
            code = e.keyCode;
        } else if (e.which) {
            code = e.which;
        }

        if (code == 38 || code == 40) {
            if (!liNum) {
                return false;
            }

            switch (code) {
                case 38:
                    //触发向上方向键键盘按钮
                    if (currentSearchBoxLiIndex <= 0) {
                        currentSearchBoxLiIndex = liNum - 1;
                    } else {
                        currentSearchBoxLiIndex--;
                    }
                    break;
                case 40:
                    //触发向下方向键键盘按钮
                    if (currentSearchBoxLiIndex < 0 || currentSearchBoxLiIndex >= (liNum - 1)) {
                        currentSearchBoxLiIndex = 0;
                    } else {
                        currentSearchBoxLiIndex++;
                    }
                    break;
            }

            $ul.find('li').removeClass('bg-warning');
            var $selectLi = $ul.children('li').eq(currentSearchBoxLiIndex);
            $selectLi.addClass('bg-warning');
            $this.val(splicSearchLiText($selectLi.children('a').text()));
            return false;
        }

    })

    /**
     * 字符串处理
     * @param keyword
     */
    function splicSearchLiText(keyword) {
        var keywordArr = keyword.split('-');
        return $.trim(keywordArr[0]);
    }

    updatehits();
})